package org.jetnuke.modules.blog;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.apache.xmlrpc.XmlRpcServer;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.modules.blog.utils.BloggerAPIHandler;
import org.jetnuke.modules.blog.utils.MetaWeblogAPIHandler;
import org.jetnuke.modules.blog.utils.MovableTypeAPIHandler;

public class XmlRPC implements IAction {
	private static XmlRpcServer mXmlRpcServer = new XmlRpcServer();
	static{
		mXmlRpcServer.addHandler("blogger", new BloggerAPIHandler());
		mXmlRpcServer.addHandler("metaWeblog",new MetaWeblogAPIHandler());
		mXmlRpcServer.addHandler("mt",new MovableTypeAPIHandler());
	}
	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		
//		BufferedReader br=new BufferedReader(new InputStreamReader(request.getInputStream()));
//		String line=null;
//		StringBuffer sb=new  StringBuffer();
//		while((line=br.readLine())!=null){
//			sb.append(line);
//			sb.append("\r\n");
//		}
//		String resultStr=sb.toString();
//		byte[] result = mXmlRpcServer.execute(new StringInputStream(resultStr));
		byte[] result = mXmlRpcServer.execute(request.getInputStream());
		

        response.setContentType("text/xml");
        response.setContentLength(result.length);

        OutputStream output = response.getOutputStream();
        output.write(result);
        output.flush();
        return null;
	}

}

class StringInputStream
extends InputStream
{
	
	private StringReader in;
	
	
	public StringInputStream( String source )
	{
		in = new StringReader( source );
	}
	
	
	public int read() throws IOException
	{
		return in.read();
	}
	
	
	public void close() throws IOException
	{
		in.close();
	}
	
	
	public synchronized void mark( final int limit )
	{
		try
		{
			in.mark( limit );
		}
		catch ( IOException ioe )
		{
			throw new RuntimeException( ioe.getMessage() );
		}
	}
	
	
	public synchronized void reset() throws IOException
	{
		in.reset();
	}
	public boolean markSupported()
	{
		return in.markSupported();
	}
}
 


